import 'package:flutter/material.dart';
import 'package:flutter_study/component/refresh/RefreshListView.dart';
import 'package:flutter_study/sqlite/SqliteHelper.dart';
import 'package:flutter_study/sqlite/note_bean_entity.dart';
import 'package:flutter_study/utils/Toast.dart';

class RefreshListViewPage extends StatefulWidget {
  @override
  _RefreshListViewPageState createState() => _RefreshListViewPageState();
}

class _RefreshListViewPageState extends State<RefreshListViewPage> {
  bool isRefresh = true;
  SqliteHelper sqliteHelper;
  List<NoteBeanEntity> noteList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    sqliteHelper = new SqliteHelper();
    getAllNote();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("下拉刷新&上拉加载"),
        ),
        body: RefreshListView(
          itemCount: noteList.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text("${noteList[index].title}"),
            );
          },
          onRefresh: () async {
            Toast.toast(context, msg: "已刷新");
            /*await getAllNote();*/
            addNote();
            return;
          },
          onLoadmore: () async {
            Toast.toast(context, msg: "上拉加载");
            /*await getAllNote();*/
            addNote();
            return;
          },
          refreshEnable: isRefresh,
        ));
  }

  void addNote() async {
    await sqliteHelper.open();
    NoteBeanEntity noteBeanEntity = new NoteBeanEntity();
    noteBeanEntity.title = noteList.length.toString();
    noteBeanEntity.content = "234";
    noteBeanEntity.noteCode = "234";
    noteBeanEntity.addTime = "2021-03-02 00:00:00";
    noteBeanEntity.updateTime = "2021-03-02 00:00:00";
    await sqliteHelper.insert(noteBeanEntity);
    getAllNote();
    await sqliteHelper.close();
  }

  void getAllNote() async {
    await sqliteHelper.open();
    List<NoteBeanEntity> list = await sqliteHelper.getAllNote(1);
    print(list.length);
    setState(() {
      noteList.clear();
      noteList.addAll(list);
    });
  }
}
